//
//  SimpleCompute.m
//  DeferredLighting
//
//  Created by Holmes Futrell on 2/9/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SimpleCompute.h"
#import "platform.h"
#import "clb_error.h"

@implementation SimpleCompute

@synthesize context, deviceID, queue;

-(id)initForGPU {

	if ( self = [super init] ) {
		
		size_t returned_size;
		
		CGLContextObj kCGLContext = CGLGetCurrentContext();              
		CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
		
		cl_context_properties properties[] = { 
			CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, 
			(cl_context_properties)kCGLShareGroup, 0 
		};
		
		// Create a context from a CGL share group
		//
		cl_int errCode = CL_SUCCESS;

		context = clCreateContext(properties, 0, 0, clLogMessagesToStdoutAPPLE, 0, &errCode);
		clb_check_error_simple(errCode);
		
		unsigned int device_count;
		cl_device_id device_ids[16];
		
		clb_check_error_simple(clGetContextInfo(context, CL_CONTEXT_DEVICES, sizeof(device_ids), device_ids, &returned_size));
		
		device_count = returned_size / sizeof(cl_device_id);
		
		int i = 0;
		int device_found = 0;
		cl_device_type device_type;	
		for(i = 0; i < device_count; i++) 
		{
			clGetDeviceInfo(device_ids[i], CL_DEVICE_TYPE, sizeof(cl_device_type), &device_type, NULL);
			if(device_type == CL_DEVICE_TYPE_GPU) 
			{
				deviceID = device_ids[i];
				device_found = 1;
				break;
			}	
		}
		
		if(!device_found)
		{
			clbfatalError("Error: Failed to locate compute device!\n");
		}
		
		
		// Report the device vendor and device name
		// 
		cl_char vendor_name[1024] = {0};
		cl_char device_name[1024] = {0};
		clb_check_error_simple(clGetDeviceInfo(deviceID, CL_DEVICE_VENDOR, sizeof(vendor_name), vendor_name, &returned_size));
		clb_check_error_simple(clGetDeviceInfo(deviceID, CL_DEVICE_NAME, sizeof(device_name), device_name, &returned_size));
		
		NSLog(@"Vendor name = %s", vendor_name);
		NSLog(@"Device name = %s", device_name);

#if RB_DEBUG == 1
		queue = clCreateCommandQueue(context, deviceID, CL_QUEUE_PROFILING_ENABLE, &errCode);
#else
		queue = clCreateCommandQueue(context, deviceID, 0, &errCode);
#endif
		
		clb_check_error_simple(errCode);
		
		return self;
	}
	return nil;
	
}

-(void)dealloc {

	clReleaseContext(context);
	clReleaseCommandQueue(queue);
	[super dealloc];
	
}

@end
